<template>
  <div class="p-2 page-flex">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="项目名称" prop="proName">
              <el-input v-model="queryParams.proName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目类型" prop="proType">
              <el-select v-model="queryParams.proType" placeholder="请选择项目类型" clearable>
                <el-option v-for="dict in project_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="项目状态" prop="proStatus">
              <el-select v-model="queryParams.proStatus" placeholder="请选择项目状态" clearable>
                <el-option v-for="dict in contract_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime" style="width: 308px">
              <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item style="margin-left: auto">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" class="table-card">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!-- 排序控件 -->
          <el-col :span="12" style="display: flex; align-items: center; gap: 8px">
            <el-select v-model="sortField" placeholder="选择排序字段" clearable style="width: 170px"
              @change="handleSortChange">
              <el-option label="项目名称" value="proName" />
              <el-option label="项目编号" value="proNumber" />
              <el-option label="项目类型" value="proType" />
              <el-option label="项目金额" value="proAmount" />
              <el-option label="业主单位" value="ownerUnit" />
              <el-option label="项目负责人" value="proLeadersName" />
              <el-option label="创建人" value="createBy" />
              <el-option label="创建时间" value="createTime" />
              <el-option label="项目状态" value="proStatus" />
            </el-select>
            <el-button v-if="sortField" :icon="sortOrder === 'asc' ? 'ArrowUp' : 'ArrowDown'" @click="toggleSortOrder"
              type="info" plain size="small" :title="sortOrder === 'asc' ? '当前为正序，点击切换为逆序' : '当前为逆序，点击切换为正序'">
              {{ sortOrder === 'asc' ? '正序' : '逆序' }}
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="projectList" border class="flex-table">
        <el-table-column type="index" label="序号" align="center" width="60"
          :index="(index) => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1" />
        <el-table-column label="项目名称" align="center" prop="proName" min-width="150" show-overflow-tooltip />
        <el-table-column label="项目编号" align="center" prop="proNumber" min-width="120" />
        <el-table-column label="项目类型" align="center" prop="proType" min-width="100">
          <template #default="scope">
            <dict-tag :options="project_type" :value="scope.row.proType || ''" />
          </template>
        </el-table-column>
        <el-table-column label="项目金额" align="center" prop="proAmount" min-width="120">
          <template #default="scope">
            {{ formatAmount(scope.row.proAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="业主单位" align="center" prop="ownerUnit" width="150" show-overflow-tooltip />
        <el-table-column label="项目负责人" align="center" prop="proLeadersName" width="120" show-overflow-tooltip />
        <el-table-column label="创建人" align="center" prop="createBy" width="100" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="150">
          <template #default="scope">
            {{ scope.row.createTime ? parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') : '' }}
          </template>
        </el-table-column>
        <el-table-column label="项目状态" align="center" prop="proStatus" min-width="100">
          <template #default="scope">
            <dict-tag :options="contract_status" :value="scope.row.proStatus || ''" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-button type="primary" link class="consume-button" @click="handleConsume(scope.row)">
              <el-icon>
                <Money />
              </el-icon>
              <span>成本消耗</span>
            </el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无项目数据" />
        </template>
      </el-table>

      <pagination class="pagination-fixed" v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { parseTime } from '@/utils/ruoyi';
import { consumePageList } from '@/api/project/init/proInfo';
import type { ProInfoQuery } from '@/api/project/init/proInfo/types';

const { proxy } = getCurrentInstance();
const router = useRouter();
const { project_type, contract_status } = toRefs<any>(proxy?.useDict('project_type', 'contract_status'));

const loading = ref(false);
const showSearch = ref(true);
const projectList = ref([]);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  proName: undefined,
  proType: undefined,
  proStatus: undefined,
  orderByColumn: undefined,
  isAsc: undefined,
  params: {}
});

// 排序相关的状态变量
const sortField = ref<string | undefined>(undefined);
const sortOrder = ref<string>('asc'); // 设置默认为正序

const formatAmount = (amount) => {
  if (amount === null || amount === undefined) return '0.00';
  return Number(amount).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};

const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bCreateTime: dateRange.value[0]?.toString(),
        eCreateTime: dateRange.value[1]?.toString()
      };
    }
    // 添加排序参数
    if (sortField.value && sortOrder.value) {
      params.orderByColumn = sortField.value;
      params.isAsc = sortOrder.value;
    }
    const res = await consumePageList(params);
    projectList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    ElMessage.error('获取项目列表失败');
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.params = {
    bCreateTime: undefined,
    eCreateTime: undefined
  };
  // 重置排序状态
  sortField.value = undefined;
  sortOrder.value = 'asc';
  queryParams.value.orderByColumn = undefined;
  queryParams.value.isAsc = undefined;
  handleQuery();
};

const handleConsume = (row) => {
  router.push(`/project/consume-edit/index/${row.id}`);
};

// 排序相关方法
const handleSortChange = (value: string) => {
  sortField.value = value;
  if (sortOrder.value !== 'asc' && sortOrder.value !== 'desc') {
    sortOrder.value = 'asc';
  }
  handleQuery();
};

const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
  handleQuery();
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
/* 页面弹性布局 */
.page-flex {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 16px);
}

.table-card {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.table-card :deep(.el-card__body) {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.flex-table {
  flex: 1;
}

.pagination-fixed {
  margin-top: 8px;
}

.consume-button {
  display: inline-flex;
  align-items: center;
  gap: 4px;

  .el-icon {
    font-size: 16px;
  }
}
</style>